<template>
	<view class="login-page">
		<view class="login-wrap">
			<view class="log">
				<view ></view>
				<h2 style="color: rgb(0,139, 250);">欢迎登录</h2>
			</view>
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="username" name="username" 
					label="用户名" placeholder="用户名"
						:rules="[{ required: true, message: '请填写用户名' }]" />
					<van-field v-model="password" type="password" name="password" 					 label="密码" placeholder="密码"
						:rules="[{ required: true, message: '请填写密码' }]" />
				</van-cell-group>
				<div style="margin: 16px;">
					<van-button round block type="primary" native-type="submit" size="normal" @click="sure">
						确定
					</van-button>
				</div>
			</van-form>
			<p @click="gologon">未注册?前往注册</p>
		</view>

	</view>
</template>

<script setup>
import api from '../../lib/request';
import {useStore} from 'vuex';
import {ref} from 'vue';
	let store = useStore()

	const username = ref('小白');
	const password = ref('123');
	let id = ref('')
	
	// 登录
	const onSubmit = (values) => {
		console.log(values);
		api.post('/user/userLogin',
		values,
		).then(res=>{
			let {token,code,data} = res
			// 存储id
			store.commit('update_uid',data.id)
			store.commit('update_name',data.username)
			store.commit('update_home',data.home)
			store.commit('update_token',token)
			store.commit('update_pass',data.password)
			uni.showToast({
				title: '登录' + (!code ? '失败' : '成功'),
				icon: 'none',
				success: () => {
					// 如果登录成功过1500秒，回到上一页
					if (code) {
						setTimeout(() => {
							uni.reLaunch({
								url:'/pages/mine/mine'
							})
						}, 1500)
						// 存储
						uni.setStorageSync('token',token)
						
					}
				}
			})
			})
	};
	
	// 前往注册页
	const gologon = () => {
		uni.navigateTo({
			url: '/pages/logon/logon'
		})
	};
	
</script>

<style>
	.login-wrap {
		position: absolute;
		top: 130rpx;
		left: calc(100vw - 350px);
	}

	.log {
		width: 370rpx;
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		margin: auto;

	}
	.log>view{
		width: calc(100vw - 140rpx);
		height: 280rpx;
		background-image: url(../../static/logo.png);
		background-size: 380rpx 380rpx;
		margin-bottom: 20rpx;
	}


	.log>h2 {
		margin-bottom: 40rpx;
	}

	p {
		position: absolute;
		right: 40rpx;
		color: #8a8a8a;
	}
</style>